<!--
 * @Descripttion: 批次管理-列表
 * @Author: 何伟伦 weilun@ssc-hn.com
 * @Date: 2024-04-10
 * @LastEditors: 何伟伦 weilun@ssc-hn.com
 * @LastEditTime: 2024-04-16
-->
<template>
  <div class="ssc-list org-position-list">
    <div class="ssc-search">
      <a-row :gutter="24">
        <a-col :span="6">
          <a-form-item label="商品">
            <a-select v-model:value="searchParam.goodId" placeholder="请选择商品" allowClear>
              <a-select-option v-for="item in goodsData" :key="item.goodId" :value="item.goodId">{{ item.goodsName }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="批次名称">
            <a-input v-model:value="searchParam.batchName" placeholder="请输入批次名称" allowClear />
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="批次编号">
            <a-input v-model:value="searchParam.batchNumber" placeholder="请输入批次编号" allowClear />
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-row justify="end">
            <a-button @click="clear()">重置</a-button>
            <a-button class="ml-4" type="primary" @click="search()">查询</a-button>
          </a-row>
        </a-col>
      </a-row>
    </div>
    <div class="ssc-table">
      <div class="ssc-table-header">
        <span class="ssc-table-header-title">批次管理</span>
        <a-button type="primary" @click="addBatch()">
          <template #icon><plus-outlined :style="{ 'font-weight': 'bold' }" /></template>
          新建
        </a-button>
      </div>
      <a-table :columns="columns" :data-source="dataList" :loading="loading" :pagination="pagination" @change="onPaginationChange">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'detail'">
            <a @click="detailBatch(record.batchId)">查看详情</a>
          </template>
          <template v-if="column.key === 'action'">
            <span>
              <a v-if="!record.channelName" @click="showChannel(record)">渠道</a>
              <a-divider v-if="!record.channelName" type="vertical" />
              <a @click="exportBatch(record)">导出</a>
              <a-divider type="vertical" />
              <a @click="editBatch(record)">编辑</a>
              <a-divider v-if="record.status !== 2" type="vertical" />
              <a-popconfirm v-if="record.status !== 2" title="确定作废此批次?" @confirm="cancelBatch(record.batchId)">
                <a class="color-error">作废</a>
              </a-popconfirm>
            </span>
          </template>
        </template>
      </a-table>
    </div>
    <div class="modal">
      <RelateChannel v-model:visible="channelEdit.visible" v-model:batchId="channelEdit.batchId" @close="channelEdit.success" />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { PlusOutlined } from '@ant-design/icons-vue'
  import { onMounted, reactive, ref } from 'vue'
  import { useRouter } from 'vue-router'

  import { requestCancelBatch, requestExportBatch, requestGetBatchGoodsList, requestGetBatchList } from '/@/api/business/tracecode/batch'
  import { HttpCodeEnum } from '/@/enums/httpEnum'
  import { useQueryPagination } from '/@/hooks/useQueryPagination'

  import RelateChannel from './components/relateChannel.vue'

  const router = useRouter()

  /** 搜索条件 */
  const searchParam = reactive({
    goodId: null,
    batchName: '',
    batchNumber: '',
  })

  const goodsData = ref<GetAllGoodsTypes.IResponse[]>([])

  /** 表格列配置 */
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      customRender: (row) => `${row.index + 1}`,
    },
    { title: '批次名称', dataIndex: 'batchName' },
    { title: '批次编号', dataIndex: 'batchNumber' },
    { title: '商品', dataIndex: 'goodsName' },
    { title: '关联渠道', dataIndex: 'channelName' },
    { title: '批次详情', dataIndex: 'detail', key: 'detail' },
    { title: '创建时间', dataIndex: 'createdTime', key: 'createdTime' },
    { title: '操作', key: 'action' },
  ]

  const { loading, queryList, dataList, pagination, onPaginationChange } = useQueryPagination<GetBatchListTypes.IRequest, GetBatchListTypes.IResponse[]>(searchParam, requestGetBatchList)

  onMounted(() => {
    queryList()
    initGoodsList()
  })

  /**
   * 重置
   */
  const clear = () => {
    searchParam.goodId = null
    searchParam.batchName = ''
    searchParam.batchNumber = ''
    search()
  }

  /**
   * 初始化商品列表
   */
  const initGoodsList = async () => {
    const { responseCode, responseData } = await requestGetBatchGoodsList({})
    if (responseCode === HttpCodeEnum.SUCCESS) {
      goodsData.value = responseData
    }
  }
  /**
   * 搜索
   */
  const search = async () => queryList({ current: 1 })

  /**
   * 新增
   */
  const addBatch = () => {
    router.push({
      path: '/code/batchManage/add',
    })
  }

  /**
   * 详细
   */
  const detailBatch = (batchId) => {
    router.push({
      path: '/code/batchManage/detail',
      query: { batchId },
    })
  }

  /**
   * 作废
   */
  const cancelBatch = async (batchId) => {
    const { responseCode } = await requestCancelBatch({ batchId })
    if (responseCode === HttpCodeEnum.SUCCESS) queryList()
  }

  /**
   * 导出
   */
  const exportBatch = async (record) => {
    const { batchId, batchName } = record
    const { responseCode, responseData } = await requestExportBatch({ batchId })
    if (responseCode === HttpCodeEnum.SUCCESS && responseData) downloadFile(responseData, batchName)
  }

  // data 数据源
  // type：格式设置
  // name是下载文件的自定义名字
  const downloadFile = (data, name) => {
    const blob = new Blob([data], { type: 'text/txt' })
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `${name}.txt`
    link.click()
    URL.revokeObjectURL(url)
  }

  /**
   * 编辑
   */
  const editBatch = (record: GetBatchListTypes.IResponse) => {
    router.push({
      path: '/code/batchManage/add',
      query: { batchId: record.batchId },
    })
  }

  /** 关联渠道弹窗 */
  const channelEdit: { visible: boolean; batchId: number; success: Function } = reactive({
    visible: false,
    batchId: 0,
    success: () => queryList(),
  })

  /**
   * 渠道配置
   */
  const showChannel = (row) => {
    channelEdit.visible = true
    channelEdit.batchId = row.batchId
  }
</script>

<style lang="less" scoped>
  .color-error {
    color: @error-color;
  }
</style>
